package com.seu.project.seuquiz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seu.project.seuquiz.common.ErrorCode;
import com.seu.project.seuquiz.constant.CommonConstant;
import com.seu.project.seuquiz.exception.BusinessException;
import com.seu.project.seuquiz.model.dto.notice.NoticeQueryRequest;
import com.seu.project.seuquiz.model.entity.Notice;
import com.seu.project.seuquiz.service.NoticeService;
import com.seu.project.seuquiz.mapper.NoticeMapper;
import com.seu.project.seuquiz.util.SqlUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
* @author lenovo
* @description 针对表【notice(公告)】的数据库操作Service实现
* @createDate 2023-07-22 19:21:16
*/
@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice>
    implements NoticeService{

    @Resource
    private NoticeMapper noticeMapper;

    @Override
    public QueryWrapper<Notice> getQueryWrapper(NoticeQueryRequest request) {
        if (request == null) {
            return null;
        }

        Long id = request.getId();
        String title = request.getTitle();
        String description = request.getDescription();
        String content = request.getContent();
        Integer status = request.getStatus();
        String sortField = request.getSortField();
        String sortOrder = request.getSortOrder();

        QueryWrapper<Notice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(id != null && id > 0, "id", id);
        queryWrapper.like(title != null, "title", "%" + title + "%");
        queryWrapper.like(description != null, "description", "%" + description + "%");
        queryWrapper.like(content != null, "content", "%" + content + "%");
        queryWrapper.eq(status != null, "status", status);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public long noticeAdd(String title, String description, String content) {
        if (StringUtils.isAnyBlank(title)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标题不能为空");
        }

        synchronized (title) {
            Notice notice = new Notice();
            notice.setTitle(title);
            notice.setDescription(description);
            notice.setContent(content);

            boolean save = this.save(notice);
            if(!save){
                throw new BusinessException(ErrorCode.SYSTEM_ERROR,"添加失败，数据库错误");
            }
            return notice.getId();
        }
    }
}




